from datetime import datetime
from typing import Dict, Any
import logging
from ..core.factor_agent import FactorAgent
from ..storage.factor_storage import FactorStorage

logger = logging.getLogger(__name__)

class FactorServiceImpl:
    """因子服务实现类（gRPC服务端核心实现）"""
    
    def __init__(self, factor_agent: FactorAgent):
        self.agent = factor_agent
        self.storage = FactorStorage()
        
    async def trigger_alert(self, factor_name: str) -> Dict[str, Any]:
        """触发因子质量警报"""
        logger.warning(f"因子质量警报触发: {factor_name}")
        return {
            "factor": factor_name,
            "status": "warning",
            "timestamp": datetime.now().isoformat(),
            "message": "检测到数据质量异常"
        }
        
    async def get_factor_metadata(self, factor_name: str) -> Dict[str, Any]:
        """获取因子元数据"""
        meta = self.storage._read_metadata(factor_name)
        return meta or {
            "error": f"未找到因子 {factor_name} 的元数据",
            "code": 404
        }
    
    async def list_active_factors(self) -> Dict[str, Any]:
        """列出所有活跃因子"""
        return {
            "factors": list(self.agent.engine.factors.keys()),
            "count": len(self.agent.engine.factors),
            "timestamp": datetime.now().isoformat()
        }